<!-- 故障率统计 -->
<template>
  <div class="app-container">
    <div class="cardBox">
      <leftTree
        ref="leftTree"
        :data="treeData"
        node-key="id"
        :default-props="defaultProps"
        search-key="typeName"
        width="200px"
        :default-expand-keys="defaultExpandKeys"
        :defalut-expand-all="true"
        @handleNodeClickAll="handleNodeClick"
      />
      <el-col id="right-content" class="right-content" :offset="0" :span="18">
        <div class="box-title">
          <el-breadcrumb separator="/" style="line-height: 50px">
            <el-breadcrumb-item
              v-for="(item, index) in breadcrumb"
              :key="index"
              >{{ item }}</el-breadcrumb-item
            >
          </el-breadcrumb>
        </div>
        <div class="search-and-button noLeftInput">
          <div class="btnList">
            <ImportFile
              url="/basic/equip/import"
              @getTableInfo="getTableInfo"
            />
            <el-button
              type
              icon="el-icon-refresh-left"
              @click="$router.push('/reload')"
              >刷新</el-button
            >
            <el-button type icon="el-icon-more">更多</el-button>
            <el-button
              type="primary"
              plain
              :icon="!show ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"
              @click="show = !show"
              >查询条件</el-button
            >
          </div>
          <div style="float: right; margin-left: 10px">
            <el-dropdown @command="handleCommand" menu-align="right">
              <el-button type="primary">
                图表
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="PublicTreeChart">
                  <i class="el-icon-s-data"></i> 柱状图(竖)
                </el-dropdown-item>
                <el-dropdown-item command="PublicHorChart">
                  <i class="el-icon-s-unfold"></i> 柱状图(横)
                </el-dropdown-item>
                <el-dropdown-item command="PublicLineChart">
                  <i class="el-icon-s-marketing"></i> 折线图
                </el-dropdown-item>
                <el-dropdown-item command="PublicPieChart">
                  <i class="el-icon-s-help"></i> 饼状图
                </el-dropdown-item>
                <el-dropdown-item command="table">
                  <i class="el-icon-s-grid"></i>显示表格</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>

        <transition name="el-zoom-in-top">
          <div v-show="show" class="more-search">
            <el-form :model="search" label-width="80px">
              <el-row>
                <el-col :xs="24" :xl="8" :md="8">
                  <el-form-item label="设备" prop="keyword">
                    <el-input
                      v-model="search.keyword"
                      clearable
                      placeholder="请输入名称或编码回车搜索"
                      @keyup.enter.native="getTableInfo()"
                      @clear="getTableInfo()"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :xl="8" :md="8">
                  <el-form-item label="故障日期" prop="time">
                    <el-date-picker
                      v-model="search.time"
                      style="width: 100%"
                      type="daterange"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期时间"
                      @change="getTableInfo()"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </transition>
        <template v-if="currentView === 'table'">
          <el-row class="table tables">
            <el-table
              ref="tableData"
              v-loading="loading"
              :data="tableData"
              stripe
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                align="center"
              ></el-table-column>
              <el-table-column
                align="center"
                type="index"
                label="索引"
                width="60px"
              />
              <el-table-column
                v-for="item in fieldList"
                :key="item.id"
                :align="item.align || 'left'"
                :prop="item.code.split(':')[1]"
                :label="item.val"
                :min-width="item.width + 'px'"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  <div
                    class="progressStyle"
                    v-if="item.code.split(':')[1] === 'failureRate'"
                  >
                    <el-progress
                      :percentage="Math.abs(row.failureRate)"
                      :stroke-width="16"
                      :color="customColors"
                      :text-inside="true"
                    />
                  </div>
                  <div
                    class="rateStyle"
                    v-else-if="item.code.split(':')[1] === 'score'"
                  >
                    <el-rate
                      v-model="row.score"
                      width="190px"
                      disabled
                      show-score
                      text-color="#ff9900"
                      score-template="{value}"
                    />
                  </div>
                  <span v-else>{{ row[item.code.split(":")[1]] }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="100px"
              ></el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <div class="table-btn-box">
              <el-button
                @click="
                  () => {
                    tableData.forEach((row) => {
                      $refs['tableData'].toggleRowSelection(row, true);
                    });
                  }
                "
                >选择全部</el-button
              >
              <el-button
                @click="
                  () => {
                    tableData.forEach((row) => {
                      $refs['tableData'].toggleRowSelection(row);
                    });
                  }
                "
                >反向选择</el-button
              >
              <el-button>
                更多菜单
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </div>
            <pagination
              ref="Pagination"
              :total="total"
              :current.sync="search.current"
              :size.sync="search.size"
              @pagination="getTableInfo"
            />
          </el-row>
        </template>

        <el-row v-if="currentView !== 'table'">
          <!-- 动态加载组件 -->
          <div
            style="width: 100%; height: calc(100vh - 250px); margin-top: 20px"
          >
            <component
              :is="currentView"
              ref="chartComponent"
              height="100%"
              width="100%"
              :table-data="chartData"
              :is-ratio="false"
            />
          </div>
        </el-row>
      </el-col>
    </div>
    <detail-tab ref="detailTab" @getTableInfo="getTableInfo" />
  </div>
</template>
<script>
import ImportFile from "@/components/ImportFile";
import Pagination from "@/components/Pagination";
import detailTab from "./components";
import leftTree from "@/components/LeftTree";
import { mapGetters } from "vuex";
import { timeFormatToString } from "@/utils/function";
import PublicTreeChart from "@/components/Charts/PublicTreeChart";
import PublicLineChart from "@/components/Charts/PublicLineChart";
import PublicHorChart from "@/components/Charts/PublicHorChart";
import PublicPieChart from "@/components/Charts/PublicPieChart";
export default {
  components: {
    leftTree,
    Pagination,
    ImportFile,
    detailTab,
    PublicTreeChart,
    PublicLineChart,
    PublicHorChart,
    PublicPieChart,
  },
  data() {
    return {
      currentView: "table", // 控制显示表格或图表
      chartData: [],
      show: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "typeName",
      },
      defaultExpandKeys: ["-1"],
      breadcrumb: ["设备类型目录"],
      loading: false,
      tableData: [],
      multipleSelection: [],
      total: 0,
      search: {
        current: 1,
        size: 20,
        objNo: "",
        keyword: "",
        time: [this.firstTime(), timeFormatToString(new Date()).slice(0, 10)],
        treeStr: "-1",
        deptId: "",
        status: "",
        beginDate: "",
        endDate: "",
      },
      typeList: [],
      customColors: [
        { color: "#f56c6c", percentage: 30 },
        { color: "#e6a23c", percentage: 60 },
        { color: "#1989fa", percentage: 80 },
        { color: "#2ed573", percentage: 100 },
      ],
    };
  },
  computed: {
    ...mapGetters(["compInfo"]),
  },
  created() {},
  async mounted() {
    await this.getTableInfo();
    await this.getAllClassify();
    this.firstTime();
  },
  methods: {
    handleCommand(command) {
      this.showView(command);
    },
    // 切换视图
    // 切换视图
    showView(view) {
      this.currentView = view;
    },

    /**
     * @description: 查询所有设备类型
     * @return {*}
     */
    async getAllClassify() {
      const res = await this.$axios.get("/equip/info/allClassify");
      if (res?.data.code === 200) {
        this.treeData = [
          {
            id: "-1",
            typeName: "设备类型目录",
            children: this.arrConvert(res.data.data),
          },
        ];
      }
    },
    arrConvert(arr) {
      let arr2 = [];
      for (let key in arr) {
        let obj = {
          typeName: arr[key],
          id: arr[key],
        };
        arr2.push(obj);
      }
      return arr2;
    },
    firstTime() {
      const now = new Date();
      const year = now.getFullYear();
      const firstDay = new Date(year.toString() + "-01-01");
      return timeFormatToString(firstDay).slice(0, 10);
    },
    timeDivide() {
      const { time } = this.search;
      if (time && time.length) {
        this.search.beginDate = time[0];
        this.search.endDate = time[1];
      } else {
        this.search.beginDate = "";
        this.search.endDate = "";
      }
      const search = {
        ...this.search,
      };
      delete search.time;
      return search;
    },
    /* 获取所有分页数据 */
    async getTableInfo(page = 1) {
      let search = this.timeDivide();
      search.current = page;
      this.loading = true;
      const res = await this.$axios.post("/equip/failure/list", search);
      if (res?.data.code === 200) {
        this.tableData = res.data.data.list;
        this.chartData = res.data.data.stat || [];

        this.total = res.data.data.total;
        setTimeout(() => {
          this.loading = false;
        }, 100);
      } else {
        this.loading = false;
      }
    },
    /**
     * @description: 树节点点击
     * @param {*} data
     * @param {*} node
     * @return {*}
     */
    handleNodeClick({ data, node }) {
      this.breadcrumb = [];
      this.returnNodeLabel(node.parent);
      this.breadcrumb.push(data.typeName);
      this.search.treeStr =
        data.typeName === "设备类型目录" ? "-1" : data.typeName;
      this.getTableInfo();
    },
    /**
     * @description: 递归获取名称
     * @param {*} node
     * @return {*}
     */
    returnNodeLabel(node) {
      if (node.parent) {
        this.breadcrumb.unshift(node.data.typeName);
        this.returnNodeLabel(node.parent);
      }
    },
    applyNoDetails(row) {
      this.$refs["detailTab"].showDialog(row);
    },
    /**
     * @description: 选中项
     * @param {*} val
     * @return {*}
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>
<style lang="scss" scoped>
.tables {
  .el-rate__icon {
    font-size: 16px !important;
    margin-right: 0 !important;
  }
  .progressStyle {
    padding-top: 6px !important;
  }
  .rateStyle {
    padding-top: 5px !important;
  }
}
</style>
